#!/usr/local/bin/perl -w
# Parsing log of GB, NC, CI ...
use strict;
use Template;
use lib "/usr/lib/cgi-bin";
use JCL;


#$|=1;
#print "Content-type: text/html\n\n";

my $tt_file = '/usr/lib/cgi-bin/src/result.html';
#-- specify absolute path must set option ABSOLUTE => 1,

#my $mmdd=$ENV{'QUERY_STRING'};

my $mmdd = shift;

$mmdd = &JCL::date_time('yesterday') unless $mmdd;

my $dir = "/home/ftpuser/$mmdd/";
my $logdir = "/home/ftpuser/";
my $log = $logdir . 'log/' . $mmdd . '.log';
my $files = &JCL::get_file_list($dir);

#--- read log file every line into array
my @logs;
my $i = 0;
open (LOG, "< $log")
 || die "Cannot open $log: $!";
 
while (<LOG>) {
   $logs[$i] = $_;
   $i++;
}
close LOG;

#-- build jobno => userid hash from scanning log
my $jobno_userid_ref = &JCL::scan_log_for_jobno_and_userid(\@logs);

#-- build releasd & releasing hash from scanning file
#my ($released_ref, $releasing_ref) = &JCL::get_released_releasing($dir, $file);

#my %file_jobs;
my @files_jobs_detail;

foreach my $element (@$files) {
  my $jobs = &JCL::get_job_list($dir, $element);
  my ($released_ref, $releasing_ref) = &JCL::get_released_releasing($dir, $element);
  my $array_ref = &JCL::file_jobs_get_result($element, $jobs, \@logs, $jobno_userid_ref, $released_ref, $releasing_ref);
  push @files_jobs_detail, @$array_ref;
}

#--- test data structure -----
#while (my ($key, $value) = each %file_jobs ) {
#  print "$key => \n";
#  print "$_\n" foreach @$value;
#}


#-- get the analyzed period of logs
my $period;
if ($logs[1] =~ m/(\d{7}) (\d{2}:\d{2}:\d{2}\.\d{2})/) {
   $period = &JCL::date_from_yday($1) . " " . substr($2, 0, 5);
}
if ($logs[$#logs -1] =~ m/(\d{7}) (\d{2}:\d{2}:\d{2}\.\d{2})/) {
   $period = $period . ' ~ ' . &JCL::date_from_yday($1) . " " . substr($2, 0, 5);
}  


#-- parsing log for matching job name to get Date Time JobNo JobName StepName RC
#--- build {job => found_log} hash
#--- key is 'job' => value is 'steps of this job array ref.' (Date Time JobNo JobName StepName RC)

my $vars = {
#    joblist    => &JCL::job_files_get_result(\%file_jobs, \@logs, $jobno_userid_ref),
    joblist    => \@files_jobs_detail,
##         must passing array ref. to template toolkit not array
    period     => $period,
#    now        => &JCL::date_time('now'),
#    file_name  => $file_name,
};


my $template = Template->new({
    INCLUDE_PATH => '/usr/lib/cgi-bin/src:/usr/lib/cgi-bin/lib',
    PRE_PROCESS  => 'config',
    ABSOLUTE     => 1,     # for specify absolute path of template file
});

$template->process($tt_file, $vars)
    || die $template->error();

